<template>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" :size="formSize" status-icon >
        <el-descriptions :column="3">
            <el-descriptions-item >
                <el-form-item label="选择项目">
                    <component :is="projectSelect" :data=ruleForm.project_id @onProjectSelect="onProjectSelect" />
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item >
                <el-form-item label="合同金额" prop="amount">
                    <el-input v-model="ruleForm.amount" />
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item >
                <el-form-item label="资金缺口" prop="gap">
                    <el-input v-model="ruleForm.gap" />
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item >
                <el-form-item label="使用（天）" prop="usage_days">
                    <el-input v-model="ruleForm.usage_days" />
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item >
                <el-form-item label="总利息" prop="interest">
                    <el-input v-model="ruleForm.interest" />
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
                <el-form-item label="使用时间" prop="usage_start_date">
                    <el-date-picker style="width: 100%;" v-model="ruleForm.usage_start_date" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期" />
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item>
                <el-form-item label="还款时间" prop="repayment_date">
                    <el-date-picker style="width: 100%;" v-model="ruleForm.repayment_date" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期" />
                </el-form-item>
            </el-descriptions-item>
            
            <el-descriptions-item :span="3">
                <el-form-item label="备注" prop="remarks">
                    <el-input v-model="ruleForm.remarks" :rows="2" type="textarea" :autosize="{ minRows: 4 }" />
                </el-form-item>
            </el-descriptions-item>
        </el-descriptions>
    </el-form>
    <div class="text-right mt10"><el-button size="small" type="primary" @click="onInsert">添加</el-button></div>
        <el-table :data="tableData" border show-summary style="width: 100%;height: 200px !important;">
        <el-table-column label="借方名称" show-overflow-tooltip>
            <template #default="scope">
                <el-input size="small" v-model="scope.row.name" />
            </template>
        </el-table-column>
        <el-table-column label="金额" show-overflow-tooltip>
            <template #default="scope">
                <el-input size="small" v-model="scope.row.amount" />
            </template>
        </el-table-column>
        <el-table-column label="利息" show-overflow-tooltip>
            <template #default="scope">
                <el-input size="small" v-model="scope.row.interest_rate" />
            </template>
        </el-table-column>
        <el-table-column label="分期数" show-overflow-tooltip>
            <template #default="scope">
                <el-input size="small" v-model="scope.row.installments" />
            </template>
        </el-table-column>
        <el-table-column label="月供" show-overflow-tooltip>
            <template #default="scope">
                <el-input size="small" v-model="scope.row.monthly_payment" />
            </template>
        </el-table-column>
        <el-table-column label="本金" show-overflow-tooltip>
            <template #default="scope">
                <el-input size="small" v-model="scope.row.principal" />
            </template>
        </el-table-column>
        <el-table-column label="总利息" show-overflow-tooltip>
            <template #default="scope">
                <el-input size="small" v-model="scope.row.total_interest" />
            </template>
        </el-table-column>
        <el-table-column label="备注" show-overflow-tooltip>
            <template #default="scope">
                <el-input size="small" v-model="scope.row.remarks" />
            </template>
        </el-table-column>
        <el-table-column label="操作" show-overflow-tooltip>
            <template #default="scope">
                <el-button size="small" link type="primary" @click="onDelete(scope.$index)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-divider />
    <div class="text-center">
        <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="loading"> 保存 </el-button>
    </div>

</template>
  
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import projectSelect from "@/components/projectSelect.vue";
import http from '../../../util/request';
import { useRouter } from 'vue-router';
import router from '../../../router';
const id:any = ref(useRouter().currentRoute.value.params.id)
const loading = ref<boolean>(false)

interface RuleForm {
    id:number
    amount:number
    project_id: number
    gap:number
    usage_days:number
    usage_start_date:string
    repayment_date:string
    interest:number
    remarks:string
    capitalizes:any
}

const formSize = ref<ComponentSize>('large')
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<RuleForm>({
    id:0,
    amount:0,
    project_id: 0,
    gap:1,
    usage_days:0,
    usage_start_date:'',
    repayment_date:'',
    interest:0,
    remarks:'',
    capitalizes:'',
})

interface Details {
    name:string
    amount:number
    interest_rate:number
    installments:number
    monthly_payment:number
    principal:number
    total_interest:number
    remarks:string
}

const Details = ref<Details>({
    name:'/',
    amount:0,
    interest_rate:0,
    installments:0,
    monthly_payment:0,
    principal:0,
    total_interest:0,
    remarks:'/'
})

const tableData = ref<Details[]>([])


const getData = () => {
    if(id.value == 0){
        return;
    }
    http.get('/capitalize/'+id.value).then((response:any)=>{
        ruleForm.value = response.data.data
        tableData.value = ruleForm.value.capitalizes
        ruleForm.value.capitalizes = ''
    })
}

const rules = reactive<FormRules<RuleForm>>({
    usage_start_date: [
        { required: true, message: '使用时间', trigger: 'blur' },
    ],
    repayment_date: [
        { required: true, message: '还款时间', trigger: 'blur' },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            loading.value = true
            let request:any = null
            ruleForm.value.capitalizes = JSON.stringify(tableData.value)
            if(ruleForm.value.id){
                request = http.patch('/capitalize',ruleForm.value)
            }else{
                request = http.put('/capitalize',ruleForm.value)
            }
            request.then((response:any)=>{
                loading.value = false
                if(response.data.code != 200){
                    ElMessage.error(response.data.msg);return
                }
                ElMessage.success(response.data.msg);
                if(id.value == 0){
                    ruleForm.value = response.data.data
                }
                router.push({ name: 'financeCapitalize'})
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const onInsert = () => {
    let data:string = JSON.stringify(Details.value)
    tableData.value.push(JSON.parse(data))
}

const onDelete = (index:number) => {
    tableData.value.splice(index,1)
}

onMounted(()=>{
    getData()
})

const onProjectSelect = (data:number) => {
    ruleForm.value.project_id = data
}

</script>
<style scoped>
.el-input{width: 100%;}
.el-tab-pane{height: calc(100vh - 25vh);overflow-y: scroll;}
::v-deep .el-form-item .el-form-item__label {
  font-size: 16px; /* 或者你想要的任何大小 */
}
::v-deep .el-tabs__item{font-size: 18px !important;}
</style>
